package com.atguigu.spzx.manger.service.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.spzx.manger.properties.MinioProperties;
import com.atguigu.spzx.manger.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {


    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        String fielUrl= null;


        try {
            // MinIo客户端.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                            .build();

            // 判断数据存储桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

            //    /20230829/45135413213201.jpg

            //创建文件夹 20230801
            String pathDir = DateUtil.format(new Date(), "yyyyMMdd");

            //随机uuid生成文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //组成文件名称
            String fileName=pathDir+"/"+uuid+file.getOriginalFilename();

            //文件上传实现
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //拼接上传后的文件路径
            fielUrl = minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+fileName;

        } catch (Exception e) {
            e.printStackTrace();
        }


        return fielUrl;
    }
}
